import { Space, Table, Tag } from 'antd';
import React, { useEffect } from 'react';
import styles from './index.less';
import { InputNumber, message } from 'antd';
import moment from 'moment';
import { HttpCode } from '#/utils/contacts.js';
import { timeIntervals } from '../../../../helper.js';
import {
  getPowerGenerationPlanList_API,
  addPowerGenerationPlan_API,
  useNewServers,
  saveYearToMonthPowerGenerationPlan,
} from '../../../../services.js';

const index = React.forwardRef((props, ref) => {
  const { queryData, handleCancel, stations, dataCount } = props;
  const [dataSource, setDataSource] = React.useState([]);
  // 生成动态列定义
  const dynamicColumns = timeIntervals.map((interval) => ({
    ...interval,
    render: (text, record, index) => {
      return (
        <InputNumber
          min={0}
          value={text}
          stringMode
          precision={3}
          step="0.001"
          onChange={(e) => {
            // 创建一个新的数据源，不要直接修改原来的
            const newData = dataSource?.map((item) =>
              item.month === record.month ? { ...item, [interval?.dataIndex]: Number(e) } : item,
            );

            // 遍历数组，更新 totalcount
            newData?.forEach((item) => {
              let sum = 0;
              // 遍历 0-23 的属性，累加值
              for (let i = 0; i <= 23; i++) {
                const key = i?.toString(); // 将数字转为字符串作为属性名
                if (item?.hasOwnProperty(key)) {
                  // 确保属性存在
                  sum += item[key];
                }
              }
              // 更新 totalcount
              item.totalcount = parseFloat(sum.toFixed(3)); // 保留两位小数
            });
            // 更新数据源
            setDataSource(newData);
          }}
        />
      );
    },
  }));

  // 定义静态列定义
  const staticColumns = [
    {
      title: '',
      dataIndex: 'month',
      key: 'month',
      fixed: 'left',
      render: (text) => <a>{text}月</a>,
    },
    {
      title: '合计',
      dataIndex: 'totalcount',
      key: 'totalcount',
      fixed: 'left',
      render: (text, record, index) => <a>{text}</a>,
    },
    // 其他静态列定义
  ];
  // 合并静态列定义和动态列定义
  const columns = [...staticColumns, ...dynamicColumns];
  // const handlehavess = (data) => {
  //   const analyzeNonZeroItems = (b) => {
  //     let count = 0;
  //     let sum = 0;
  //     for (let i = 0; i <= 23; i++) {
  //       const key = i.toString();
  //       if (b.hasOwnProperty(key) && b[key] !== 0) {
  //         count++;
  //         sum += b[key];
  //       }
  //     }
  //     return {
  //       count,
  //       sum,
  //     };
  //   };

  //   const arr = data.map((item, index) => {
  //     const result = analyzeNonZeroItems(item);
  //     const availableHours = 24 - result.count;
  //     const remainingValue = result.sum ? dataCount[index] - result.sum : dataCount[index];
  //     const calculatedValue = Number(parseFloat(remainingValue / availableHours).toFixed(3));
  //     return {
  //       month: item.month,
  //       totalcount: dataCount[index],
  //       0: item[0] === 0 ? calculatedValue : item[0],
  //       1: item[1] === 0 ? calculatedValue : item[1],
  //       2: item[2] === 0 ? calculatedValue : item[2],
  //       3: item[3] === 0 ? calculatedValue : item[3],
  //       4: item[4] === 0 ? calculatedValue : item[4],
  //       5: item[5] === 0 ? calculatedValue : item[5],
  //       6: item[6] === 0 ? calculatedValue : item[6],
  //       7: item[7] === 0 ? calculatedValue : item[7],
  //       8: item[8] === 0 ? calculatedValue : item[8],
  //       9: item[9] === 0 ? calculatedValue : item[9],
  //       10: item[10] === 0 ? calculatedValue : item[10],
  //       11: item[11] === 0 ? calculatedValue : item[11],
  //       12: item[12] === 0 ? calculatedValue : item[12],
  //       13: item[13] === 0 ? calculatedValue : item[13],
  //       14: item[14] === 0 ? calculatedValue : item[14],
  //       15: item[15] === 0 ? calculatedValue : item[15],
  //       16: item[16] === 0 ? calculatedValue : item[16],
  //       17: item[17] === 0 ? calculatedValue : item[17],
  //       18: item[18] === 0 ? calculatedValue : item[18],
  //       19: item[19] === 0 ? calculatedValue : item[19],
  //       20: item[20] === 0 ? calculatedValue : item[20],
  //       21: item[21] === 0 ? calculatedValue : item[21],
  //       22: item[22] === 0 ? calculatedValue : item[22],
  //       23: item[23] === 0 ? calculatedValue : item[23],
  //     };
  //   });
  //   setDataSource(arr);
  // };

  const handlehave = (data) => {
    const analyzeNonZeroItems = (b) => {
      let count = 0;
      let sum = 0;
      for (let i = 0; i <= 23; i++) {
        const key = i.toString();
        if (b.hasOwnProperty(key) && b[key] !== 0) {
          count++;
          sum += b[key];
        }
      }
      return {
        count,
        sum,
      };
    };

    const arr = data.map((item, index) => {
      const result = analyzeNonZeroItems(item);
      const availableHours = 24 - result.count;
      const remainingValue = result.sum ? dataCount[index] - result.sum : dataCount[index];
      const calculatedValue = Number(parseFloat(remainingValue / availableHours).toFixed(3));
      const quotient = Math.floor(remainingValue / (availableHours - 1));
      const remainder = remainingValue % availableHours;
      const adjustedRemainder = remainingValue % (availableHours - 1);
      return {
        month: item.month,
        totalcount: dataCount[index] ? dataCount[index] : 0,
        0: item[0] === 0 ? (quotient > 0 ? quotient : 0) : item[0],
        1: item[1] === 0 ? (quotient > 0 ? quotient : 0) : item[1],
        2: item[2] === 0 ? (quotient > 0 ? quotient : 0) : item[2],
        3: item[3] === 0 ? (quotient > 0 ? quotient : 0) : item[3],
        4: item[4] === 0 ? (quotient > 0 ? quotient : 0) : item[4],
        5: item[5] === 0 ? (quotient > 0 ? quotient : 0) : item[5],
        6: item[6] === 0 ? (quotient > 0 ? quotient : 0) : item[6],
        7: item[7] === 0 ? (quotient > 0 ? quotient : 0) : item[7],
        8: item[8] === 0 ? (quotient > 0 ? quotient : 0) : item[8],
        9: item[9] === 0 ? (quotient > 0 ? quotient : 0) : item[9],
        10: item[10] === 0 ? (quotient > 0 ? quotient : 0) : item[10],
        11: item[11] === 0 ? (quotient > 0 ? quotient : 0) : item[11],
        12: item[12] === 0 ? (quotient > 0 ? quotient : 0) : item[12],
        13: item[13] === 0 ? (quotient > 0 ? quotient : 0) : item[13],
        14: item[14] === 0 ? (quotient > 0 ? quotient : 0) : item[14],
        15: item[15] === 0 ? (quotient > 0 ? quotient : 0) : item[15],
        16: item[16] === 0 ? (quotient > 0 ? quotient : 0) : item[16],
        17: item[17] === 0 ? (quotient > 0 ? quotient : 0) : item[17],
        18: item[18] === 0 ? (quotient > 0 ? quotient : 0) : item[18],
        19: item[19] === 0 ? (quotient > 0 ? quotient : 0) : item[19],
        20: item[20] === 0 ? (quotient > 0 ? quotient : 0) : item[20],
        21: item[21] === 0 ? (quotient > 0 ? quotient : 0) : item[21],
        22: item[22] === 0 ? (quotient > 0 ? quotient : 0) : item[22],
        23: item[23] === 0 ? (adjustedRemainder > 0 ? adjustedRemainder : 0) : item[23],
      };
    });
    setDataSource(arr);
  };

  const hanldleNoValue = (data) => {
    const arr = data.map((item, index) => {
      const availableHours = 24;
      const remainingValue = dataCount[index];
      const calculatedValue = Math.floor(remainingValue / (availableHours - 1));
      const adjustedRemainder = remainingValue % (availableHours - 1);

      return {
        month: item.month,
        totalcount: dataCount[index] ? dataCount[index] : 0,
        0: item[0] === 0 ? (calculatedValue ? calculatedValue : 0) : item[0],
        1: item[1] === 0 ? (calculatedValue ? calculatedValue : 0) : item[1],
        2: item[2] === 0 ? (calculatedValue ? calculatedValue : 0) : item[2],
        3: item[3] === 0 ? (calculatedValue ? calculatedValue : 0) : item[3],
        4: item[4] === 0 ? (calculatedValue ? calculatedValue : 0) : item[4],
        5: item[5] === 0 ? (calculatedValue ? calculatedValue : 0) : item[5],
        6: item[6] === 0 ? (calculatedValue ? calculatedValue : 0) : item[6],
        7: item[7] === 0 ? (calculatedValue ? calculatedValue : 0) : item[7],
        8: item[8] === 0 ? (calculatedValue ? calculatedValue : 0) : item[8],
        9: item[9] === 0 ? (calculatedValue ? calculatedValue : 0) : item[9],
        10: item[10] === 0 ? (calculatedValue ? calculatedValue : 0) : item[10],
        11: item[11] === 0 ? (calculatedValue ? calculatedValue : 0) : item[11],
        12: item[12] === 0 ? (calculatedValue ? calculatedValue : 0) : item[12],
        13: item[13] === 0 ? (calculatedValue ? calculatedValue : 0) : item[13],
        14: item[14] === 0 ? (calculatedValue ? calculatedValue : 0) : item[14],
        15: item[15] === 0 ? (calculatedValue ? calculatedValue : 0) : item[15],
        16: item[16] === 0 ? (calculatedValue ? calculatedValue : 0) : item[16],
        17: item[17] === 0 ? (calculatedValue ? calculatedValue : 0) : item[17],
        18: item[18] === 0 ? (calculatedValue ? calculatedValue : 0) : item[18],
        19: item[19] === 0 ? (calculatedValue ? calculatedValue : 0) : item[19],
        20: item[20] === 0 ? (calculatedValue ? calculatedValue : 0) : item[20],
        21: item[21] === 0 ? (calculatedValue ? calculatedValue : 0) : item[21],
        22: item[22] === 0 ? (calculatedValue ? calculatedValue : 0) : item[22],
        23: item[23] === 0 ? (adjustedRemainder ? adjustedRemainder : 0) : item[23],
      };
    });

    setDataSource(arr);
  };

  const getTableData = async () => {
    let info = {
      stationId: queryData?.unit,
      planYear: moment(queryData?.date).format('YYYY'),
    };
    try {
      const res = await getPowerGenerationPlanList_API(info);
      if (res?.statusCode === HttpCode?.SUCCESS) {
        if (res?.data?.timePeriodsPlanDataDetail?.length) {
          const bt = res?.data?.timePeriodsPlanDataDetail?.reduce((acc, item, index) => {
            const month = item?.planMonth;
            const hour = item?.planHour; // 将 planHour 作为键
            const value = item?.planValue;
            // 找到或创建对应的月对象
            let monthObj = acc?.find((m) => m?.month === month);
            if (!monthObj) {
              monthObj = { month, totalcount: 0 }; // 初始化 totalcount
              acc.push(monthObj);
            }
            // 添加小时和值
            monthObj[hour] = value;
            // 计算 totalcount
            if (hour >= 0 && hour <= 23) {
              monthObj.totalcount += value;
            }
            return acc;
          }, []);
          // 格式化 totalcount 保留小数点后三位
          const formattedB = bt?.map((monthObj) => {
            monthObj.totalcount = Number(monthObj.totalcount.toFixed(3));
            return monthObj;
          });
          // setDataSource(formattedB);
          handlehave(formattedB);
        } else {
          const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((month) => {
            return {
              month,
              totalcount: 0,
              0: 0,
              1: 0,
              2: 0,
              3: 0,
              4: 0,
              5: 0,
              6: 0,
              7: 0,
              8: 0,
              9: 0,
              10: 0,
              11: 0,
              12: 0,
              13: 0,
              14: 0,
              15: 0,
              16: 0,
              17: 0,
              18: 0,
              19: 0,
              20: 0,
              21: 0,
              22: 0,
              23: 0,
            };
          });
          // setDataSource(data);
          hanldleNoValue(data);
        }
      } else {
        message.error(res.message);
      }
    } catch (error) {
      throw new Error(error);
    }
  };

  useEffect(() => {
    getTableData();
  }, []);

  // 使用 useImperativeHandle 来暴露方法给父组件
  React.useImperativeHandle(ref, () => ({
    handleSubmit,
  }));

  const convertToDFormat = (arr) => {
    const dt = [];
    arr?.forEach((record) => {
      for (let hour = 0; hour < 24; hour++) {
        dt.push({
          planHour: hour,
          planMonth: record.month,
          planValue: parseFloat(record[hour].toFixed(3)), // 确保小数点后最多两位
        });
      }
    });
    return dt;
  };

  //通过stationId去查找marketId
  const getMarketId = (unit) => {
    const result = stations.find((item) => item.stationId === unit);
    let _marketId = '';
    if (result) {
      _marketId = result.marketId;
    }
    return _marketId;
  };
  /**
   * 提交
   */
  const handleSubmit = async () => {
    const data = convertToDFormat(dataSource);
    const info = {
      planDetails: data,
      stationId: queryData.unit,
      planYear: moment(queryData.date).format('YYYY'),
    };
    // 将 dataSource 转换为对象数组，其中 key 是月份，value 是总和
    const monthEleObj = dataSource.reduce((acc, it, index) => {
      const monthKey = index + 1; // 月份从1开始
      acc[monthKey] = it.totalcount === 0 ? '0' : it.totalcount;
      return acc;
    }, {});
    // 计算总和
    const total = Object.values(monthEleObj).reduce((sum, value) => {
      return sum + (typeof value === 'string' ? parseFloat(value) : value);
    }, 0);

    const param = {
      marketId: getMarketId(queryData?.unit),
      monthEle: monthEleObj,
      stationId: queryData?.unit,
      valueType: 'numerical',
      year: moment(queryData.date).format('YYYY'),
      publish: false,
      yearEle: total,
    };
    const marketId = getMarketId(queryData?.unit);
    if (useNewServers.includes(marketId)) {
      param.marketId = marketId;
    }
    const res = await addPowerGenerationPlan_API(info);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const res = await saveYearToMonthPowerGenerationPlan(param, marketId);
      if (res?.statusCode === HttpCode.SUCCESS) {
        handleCancel();
      } else {
        message.error(res.message);
      }
    } else {
      message.error(res.message);
    }
  };

  return (
    <Table
      columns={columns}
      dataSource={dataSource}
      className={styles.timeSlotTable_style}
      pagination={false}
      bordered={true}
      scroll={{
        x: 'calc(700px + 50%)',
      }}
    />
  );
});

export default index;
